package com.czt.mail.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.profile.DefaultProfile;

import java.net.URL;
import java.util.Date;

/**
 * @author czt
 * @version 1.0
 * {@desc}
 * @date 2024/9/12 15:05
 */
public class Oss {

    public static void main(String[] args) {
        // STS 配置
        String endpoint = "";
        String roleArn = "";
        String roleSessionName = "";

        // 创建 STS 客户端
        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", "", "");
        IAcsClient client = new DefaultAcsClient(profile);

        // 创建 AssumeRole 请求
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setSysEndpoint(endpoint);
        request.setRoleArn(roleArn);
        request.setRoleSessionName(roleSessionName);

        try {
            // 获取临时凭证
            AssumeRoleResponse response = client.getAcsResponse(request);
            String temporaryAccessKeyId = response.getCredentials().getAccessKeyId();
            String temporaryAccessKeySecret = response.getCredentials().getAccessKeySecret();
            String securityToken = response.getCredentials().getSecurityToken();

            // 使用临时凭证生成 OSS 签名 URL
            String signedUrl = generateSignedUrl(temporaryAccessKeyId, temporaryAccessKeySecret, securityToken, "unreal", "Win64", "1.0.0");
            System.out.println("Generated URL: " + signedUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 使用临时凭证生成签名 URL 的方法
    public static String generateSignedUrl(String accessKeyId, String accessKeySecret, String securityToken, String appPlatform, String appTerminal, String versionNum) {
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        String bucketName = "yysj-app-version";
        // 创建 OSS 客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);

        // 拼接对象路径
        String objectName = appPlatform + "/" + appTerminal + "/" + versionNum + ".patch";

        try {
            // 设置 URL 的有效期
            Date expiration = new Date(System.currentTimeMillis() + 3 * 24 * 60 * 60 * 1000);

            // 生成签名 URL
            URL signedUrl = ossClient.generatePresignedUrl(bucketName, objectName, expiration);

            return signedUrl.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭 OSS 客户端
            ossClient.shutdown();
        }
    }
}
